const express = require('express')
const router = express.Router()
const db = require('../../connection/Connection')
const jwt = require('jsonwebtoken')
const moment = require('moment')
const SECRET = 'asdfta219*&%^jWJSHFJ'


router.post('/updateSalary', async (req, res) => {
    //token
    const result = jwt.verify(req.body.token, SECRET)
    let sql = 'select departmentId from user_role where username = ?'
    db.base(sql, result.username, response_temp => {
        console.log(req.body)
        if (response_temp != null && response_temp.length == 1) {
            sql = 'select workNumber from department_employees WHERE departmentId = ?'
            db.base(sql, response_temp[0].departmentId, response_temp => {
                flag = false
                for (let i = 0; i < response_temp.length; i++) {
                    if (req.body.workNumber == response_temp[i].workNumber) {
                        flag = true
                    }
                }
                console.log(flag)
                //为true 说明员工是本部门员工
                if (flag) {
                    //获取员工薪资id
                    sql = 'SELECT salary_id FROM employees WHERE work_number = ?'
                    db.base(sql, req.body.workNumber, response_temp1 => {
                        console.log(response_temp1)
                        sql = 'INSERT INTO salary_change (salary_id,change_type,reason,amount,occur_time) VALUES (?,?,?,?,?)'
                        var time = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
                        let data = [
                            response_temp1[0].salary_id,
                            req.body.change_type,
                            req.body.reason,
                            req.body.des_salary,
                            time
                        ]
                        db.base(sql, data, response_temp => {

                            if (response_temp != null && response_temp.affectedRows == 1) {
                                res.json({
                                    result: "success"
                                })
                            } else {
                                res.json({
                                    result: 'error'
                                })
                            }
                        })
                    })
                } else {
                    res.json({
                        result: 'error'
                    })
                }
            })
        } else {
            res.json({
                result: 'error'
            })
        }
    })
})

module.exports = router
